/*
 * @Author: za-pangzhongwu
 * @Date: 2018-11-10 11:07:23
 * @Description: ''
 * @Last Modified by: zoushiyong
 * @Last Modified time: 2018-11-26 11:07:56
 * @ToDo: ''
 */
import React from 'react'
import { Form, Select, Input, Modal, Row, Col } from 'antd'
import { connect } from 'mirrorx'
import api from '../../../api/index'
const FormItem = Form.Item
const Option = Select.Option

class NewPassword extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      roleId: '',
      confirmDirty: false
    }
    // 修改账户及账户列表渲染
    this.handleSubmit = this.handleSubmit.bind(this)
    // 密码校验
    this.validateToNextPassword = this.validateToNextPassword.bind(this)
    // 确认密码校验
    this.compareToFirstPassword = this.compareToFirstPassword.bind(this)
    // 除默认角色创建自定义角色及权限，跳转至角色管理
    this.handleConfirmBlur = this.handleConfirmBlur.bind(this)
    // 获取下拉框Role
    this.changeRole = this.changeRole.bind(this)
  }
  changeRole (currency) {
    this.setState({
      roleId: currency
    })
  }
  handleConfirmBlur (e) {
    const value = e.target.value
    this.setState({ confirmDirty: this.state.confirmDirty || value })
  }
  compareToFirstPassword (rule, value, callbackFun) {
    const form = this.props.form
    if (value && value !== form.getFieldValue('newPassword')) {
      callbackFun('Password didn’t match, please try again')
    } else {
      callbackFun()
    }
  }
  validateToNextPassword (rule, value, callback) {
    const form = this.props.form
    if (value && this.state.confirmDirty) {
      form.validateFields(['confirm'], { force: true })
    }
    callback()
  }
  handleSubmit (e) {
    e.preventDefault()
    const { hideModal, queryAccount } = this.props
    const { roleId } = this.state
    this.props.form.validateFields((err, values) => {
      if (!err) {
        if (values.newPassword !== values.confirmNewPassword) {
        } else {
          T.ajax({// 修改密码
            url: api.changeSubAccountPassword.path,
            loading: true,
            data: {
              'userId': this.props.roles,
              'password': values.newPassword
            }
          }).then(res => {
            if (res.code === 0) {
              T.ajax({// 修改角色
                url: api.updateUserRoleByUserId.path,
                loading: true,
                data: {
                  'userId': this.props.roles,
                  'roleId': roleId === '' ? this.props.roleId : roleId
                }
              }).then(res => {
                this.props.success()
                hideModal()
                if (res.code === 0) {
                  queryAccount()// 重新获取一遍账户列表
                }
              })
            }
          })
          this.props.form.resetFields()// 清空表单
          hideModal()
        }
      }
    })
  }
  render () {
    const { getFieldDecorator } = this.props.form
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    }
    let { roleList } = this.props
    if (!this.props.visible) {
      this.props.form.resetFields()
    }
    return (
      <Modal
        title='Sub-account Edit'
        className='change-password'
        visible={this.props.visible}
        onOk={this.handleSubmit}
        onCancel={this.props.hideModal}
        okText='Confirm'
        cancelText='Cancel'
      >
        <Form>
          <FormItem
            {...formItemLayout}
            label='New password'
            className='antd-inpu-change'
          >
            {getFieldDecorator('newPassword', {
              rules: [{ required: true, message: 'Please enter the password' },
                { pattern: T.regObj['password'], message: 'The password is not valid' },
                {
                  validator: this.validateToNextPassword
                }]
            })(
              <Input type='password' placeholder='Enter the new password' maxLength='50' />
            )}
          </FormItem>
          <Row>
            <Col span={8} />
            <Col span={16}><p>Use 8 or more characters with a mix of ONLY letters & numbers</p></Col>
          </Row>
          <FormItem
            {...formItemLayout}
            label='Confirm new password'
            className='antd-inpu-change'
          >
            {getFieldDecorator('confirmNewPassword', {
              rules: [
                { required: true, message: 'Please enter the password' }, {
                  validator: this.compareToFirstPassword
                }]
            })(
              <Input
                className='mt10 mb10'
                type='password'
                placeholder='Please enter your password again'
                onBlur={this.handleConfirmBlur} maxLength='50' />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label='Role'
          >
            {getFieldDecorator('role', {
              initialValue: this.props.role,
              rules: [{ required: true, message: 'Please select your gender' }]
            })(
              <Select
                placeholder='Select a option and change input text above'
                onChange={this.changeRole}
              >
                {
                  roleList && roleList.map((item) => (
                    <Option key={item.roleId}>{item.roleName}</Option>
                  ))
                }
              </Select>
            )}
          </FormItem>
          <Row>
            <Col span={8} />
            <Col span={16}><p className='password-zou'>Please be noted that changing the rloe may lead to changes of authorizations</p></Col>
          </Row>
        </Form>
      </Modal>
    )
  }
}

const ChangePassword = Form.create()(NewPassword)
export default connect(state => {
  return state.mainModel
})(ChangePassword)
